package com.itheima.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()    //开启http的安全控制
//                .antMatchers("/index.html").permitAll()
                .antMatchers("/login.html").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/admin/admin.html").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()    //自定义登录页
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
//                .usernameParameter("username")
//                .passwordParameter("password")
                .successHandler(new MyAuthenticationSuccessHandler())
                .failureHandler(new MyAuthenticationFailureHandler())
                .and().csrf().disable()
                .sessionManagement()
                .maximumSessions(1)
                .expiredUrl("/login.html")
        ;
    }

    @Bean
    public UserDetailsService userDetailsService(){
        return new MyUserDetailsService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                // 指定UserDetailsService的实现类，目的就是加载用户名和密码
                .userDetailsService(userDetailsService())
                // 指定加密算法
                .passwordEncoder(new BCryptPasswordEncoder())
        ;
    }

    public static void main(String[] args) {
        String password=new BCryptPasswordEncoder().encode("1234");
        System.out.println(password);
    }
}
